package com.invest.config;

import com.invest.service.UserService;
import com.invest.utils.type.SystemUserRoleType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * Created by evan on 2016/3/6.
 */
@Configuration
@EnableWebSecurity
@AutoConfigureAfter(DbAuthenticationProvider.class)
public class WebSecurityConfig
       extends WebSecurityConfigurerAdapter {

    //in memory
    public static final  String SPRING_ROLE_PREFIX = "ROLE_";

   @Autowired
    private UserService userService;

    @Autowired
    private DbAuthenticationProvider dbAuthenticationProvider;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(dbAuthenticationProvider);
        auth.userDetailsService(userService);

    }

   /* @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("user").password("a").roles(UserRole.user.getCode())
                .and()
                .withUser("user").password("a").roles(UserRole.user.getCode())
                ;

    }
*/
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.headers().frameOptions().sameOrigin();
        //关闭站点攻击
        http.csrf().disable();
        //认证
        http.userDetailsService(userService)
                .authenticationProvider(dbAuthenticationProvider)
                .authorizeRequests()
                .antMatchers("/", "/public/**").permitAll()
                .antMatchers("/admin/**").hasAuthority(SystemUserRoleType.SYS_ADMIN.name())
                .antMatchers("/invest/**").hasAuthority(SystemUserRoleType.SYS_USER.name())
                .anyRequest().fullyAuthenticated()
                .and()
                .formLogin()
                .loginPage("/login")
                .failureUrl("/login?error")
                .defaultSuccessUrl("/home")
                .permitAll()
                .and()
                .logout()
                .logoutUrl("/logout")
                .deleteCookies("remember-me")
                .logoutSuccessUrl("/login")
                .permitAll()
                .and()
                .rememberMe()
                .and().exceptionHandling().accessDeniedPage("/login")
                ;
        ;
    }
}
